import XLSX from 'xlsx'
export function exportDataHandler(data: any[], fields: Record<string, string>, filename: string = '数据表格.xlsx') {
  const wb = XLSX.utils.book_new();
  const jsonWs = XLSX.utils.json_to_sheet(data.map(item => {
    let newItem: Record<string, string> = {}
    for (let i in fields) {
      if (i in item) {
        newItem[fields[i]] = item[i]
      }
    }
    return newItem
  }));
  // @ts-ignore
  // jsonWs['!protect'] = {}
  // jsonWs['!protect'].password = '1111'
  // jsonWs['!protect'].selectLockedCells = false
  // jsonWs['!protect'].selectUnlockedCells = false
  // jsonWs.sheetProtection = {
  //   password: "custom"
  // }
  XLSX.utils.book_append_sheet(wb, jsonWs, 'sheet1');
  XLSX.writeFile(wb, filename);
};

/**
   * 导入execl数据
  */
export function ImportExecl<T extends Record<string, string>>(dataMap: T, hooks?: (data: any, dataMap: T) => any) : Promise<{ formatedData: unknown[], file: File }>{
  return new Promise((resolve, reject) => {
    const inputElement = document.createElement('input')
    inputElement.type = 'file'
    inputElement.click();
    inputElement.accept = '.xlsx, .xls'
    inputElement.addEventListener('change', async (e) => {
      // @ts-ignore
      const files = e.target?.files;
      const file = files[0]
      readExecl(file).then(execlData => {
        console.log('execlData: ', execlData, dataMap);
        const formatedData: unknown[] = execlData.map(data => {
          let temp = data
          // 支持通过钩子格式化数据
          if (hooks) {
            const result = hooks(data, dataMap)
            // 支持在读取数据后动态修改fileds
            if (result.fields) {
              dataMap = result.fields
              temp = result.data
            } else {
              temp = result
            }
          }
          return formatExeclData(temp, dataMap)
        })
        // const formatedData = formatExeclData(execlData, dataMap)
        console.log('format-execlData: ', formatedData);
        resolve({
          formatedData: formatedData.flat(),
          file
        })
      })
    })
  })
}

export async function parseExecl(file: File, dataMap: Record<string, string>) {
  return readExecl(file).then(_ => formatExeclData(_, dataMap))
}

// 读取execl内容
export function readExecl(file: File): Promise<any[]> {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.onload = (ev) => {
      try {
        const data = fileReader.result
        const workbook = XLSX.read(data, {
          type: 'binary'
        })
        // 生成json表格内容
        const ws = workbook.SheetNames.map(wsname => XLSX.utils.sheet_to_json(workbook.Sheets[wsname], { blankrows: false }))
        resolve(ws)
      } catch (e) {
        reject(e)
        return false
      }
    }
    fileReader.readAsBinaryString(file);
  })
}

// {
//   "pay_id": "资金发放批单编号",
//   "member_id": "农户编号",
//   "s_a_id": "行政地区编号",
//   "s_a_nam": "所在村社",
//   "pay_size_total": "补贴面积",
//   "member_nam": "户主姓名",
//   "member_bank_num": "收款账号",
//   "member_bank_code": "开户银行",
//   "pay_total": "补贴金额（元）",
//   "bk_pay_price": "已支付金额（元）",
//   "bk_id": "付款银行",
//   "bk_order_id": "银行付款业务单编号",
//   "bk_pay_time": "付款时间",
//   "pay_statu": "支付进度",
//   "pay_price_total": "补贴面积(亩)",
//   "pay_price": "补贴标准(元/亩)",
//   "readme": "银行备注"
// }

// 格式化execl数据
export function formatExeclData(data: any[], dataMap: Record<string, string>): any[] {
  const MapTable:  Record<string, string> = dataMap
  let newMapTable: Record<string, string> = {}
  // 交换key value
  Object.keys(MapTable).forEach((key: string) => {
    // 替换换行符
    const value = MapTable[key]
    newMapTable[value] = key
  })
  return data.map(item => {
    let newItem: Record<string, string> = {}
    let formatItem: Record<string, string> = {}
    // 处理换行符
    for (let i in item) {
      formatItem[i.replace(/\n/g, '')] = typeof item[i] === 'undefined' ? '' : item[i] // item[i] || ''
    }
    for (let i in newMapTable) {
      newItem[newMapTable[i]] = typeof formatItem[i] === 'undefined' ? '' : formatItem[i]
    }
    return newItem
  })
}